#include <iostream>
#include <winsock2.h>

using std::cout;
using std::cin;
using std::string;
using std::endl;
typedef struct Date {
    float m1;
    float m2;
    float m3;
    float m_roll;
    float m_pitch;
    float m_rotate;
} Datablock;

int ReceiveData(SOCKET conn, char *recvData, int sendBytes, int flags) {
    int recvBytes = 0;

    while (recvBytes != sendBytes) {
        int ret = recv(conn, recvData + recvBytes, sendBytes - recvBytes, flags);   // 循环接收网络数据
        if (ret > 0)
            recvBytes = recvBytes + ret;
    };

    return recvBytes;
}

int SendData(SOCKET s, const char *buf, int len, int flags) {
    //sendmutex_decoder.lock();
    int ret = 0;
    if (len)
        ret = send(s, buf, len, flags);
    //printf("Send: \tSocket = %d, \tret = %d, \tError = %d, \tsendlen = %d\n", s, ret, GetLastError(), len);
    //sendmutex_decoder.unlock();
    return ret;
}

int main() {
    cout << "server start" << endl;
    //初始化winsock   
    WSADATA wsaD;
    WSAStartup(MAKEWORD(1, 1), &wsaD);
    //创建监听套接字   
    SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    // 绑定主机地址和监听套接字   
    struct sockaddr_in my_addr;   //主机地址   
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(8088); //指定端口   
    my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    bind(slisten, (struct sockaddr *) &my_addr, sizeof(my_addr));
    //启动监听   
    listen(slisten, 5);    //5是最大连接数
    //开始接收数据
    struct sockaddr_in c_addr;  //客户地址   
    int addr_len = sizeof(c_addr);
    SOCKET sconnect = accept(slisten, (struct sockaddr *) &c_addr, &addr_len); //通过监听套接字创建连接套接字
    cout << "client connect......" << endl;

    Datablock send_data = {1, 2, 3, 4, 5, 6}, recv_data;
    while (true) {
        int len = ReceiveData(sconnect, (char *)&recv_data, sizeof(Datablock), 0);  //通过连接套接字接收数据
        if (len > 0)
        {
            cout << recv_data.m1 << endl;
            cout << recv_data.m2 << endl;
            cout << recv_data.m3 << endl;
            cout << recv_data.m_roll << endl;
            cout << recv_data.m_pitch << endl;
            cout << recv_data.m_rotate << endl;
        }
        SendData(sconnect, (char *) &recv_data, sizeof(Datablock), 0);  //字符串还有个结束标志
    }

    return 0;
}
